package com.gsafety.library.Net.RetrofitExt.adapters;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import com.gsafety.library.Net.RetrofitExt.common.SCallBack;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;

import retrofit2.Call;
import retrofit2.CallAdapter;

public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<R>>
{
    private Type responseType;

    public LiveDataCallAdapter(Type responseType)
    {
        this.responseType = responseType;
    }

    @Override
    public Type responseType()
    {
        return responseType;
    }

    @Override
    public LiveData<R> adapt(final Call<R> call)
    {
        LiveData<R> result = new LiveData<R>()
        {
            private AtomicBoolean started = new AtomicBoolean(false);

            @Override
            protected void onActive()
            {
                super.onActive();

                if (started.compareAndSet(false, true))
                {
                    call.enqueue(new SCallBack<R>()
                    {
                        @Override
                        public void onSuccess(@NonNull R result)
                        {
                            postValue(result);
                        }

                        @Override
                        public void onFail(Call<R> call, Throwable t)
                        {
                            postValue(null);
                            super.onFail(call, t);
                        }

                        @Override
                        public void onFinally()
                        {
                            super.onFinally();
                        }
                    });
                }

            }
        };
        return result;
    }
}
